//
// Created by scl on 2024/4/5.
//
#include "streaming.grpc.pb.h"
#include <grpc++/grpc++.h>
#include <iostream>
#include <string>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using example::Point;
using example::PointCloud;
using example::StatusResponse;
using example::StreamService;

class StreamServiceImpl final : public StreamService::Service
{
 public:
	Status SendPointCloud(ServerContext* context, const PointCloud* request, StatusResponse* response) override
	{
		pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);

		for (const auto& point : request->points())
		{
			cloud->push_back(pcl::PointXYZ(point.x(), point.y(), point.z()));
		}

		std::cout << "Received a PointCloud with " << cloud->size() << " points." << std::endl;

		// 处理点云数据
		// [在这里添加处理点云的代码]

		response->set_message("PointCloud received successfully");
		return Status::OK;
	}
};

void RunServer(const std::string& server_address = "0.0.0.0:50051")
{
	StreamServiceImpl service;

	ServerBuilder builder;
	// 设置接收消息的最大大小为1G
	builder.SetMaxReceiveMessageSize(1000 * 1024 * 1024);

	builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
	builder.RegisterService(&service);

	std::unique_ptr<Server> server(builder.BuildAndStart());
	std::cout << "Server listening on " << server_address << std::endl;

	server->Wait();
}

int main(int argc, char** argv)
{
	RunServer();
	return 0;
}
